from luckey.net.stun import stun, nat
from twisted.internet import reactor
from luckey          import params

def printA(s):
    print "print a", s
    return s

import sys
import time
import threading
from twisted.internet import reactor
from twisted.internet import defer
from twisted.protocols import wire
from twisted.internet.protocol import Factory
from twisted.python import threadable

threadable.init( with_threads=1)

class ReactorFacade:

    def __init__( self ):
        self.reactorThread = threading.Thread(
            target=reactor.run,
            name="ReactorThread",
            kwargs={'installSignalHandlers':0},
            )
        self.defered = nat.getLocalIPAddress().addCallback(self.setLocalIP)
        print "add callback"
    
    def setLocalIP(self, ip):
        params.LOCALIP = ip
        print "set local ip to:",ip 

    def start(self):
        # assume not yet started
        print "Facade: starting..."
        self.reactorThread.start()
        print "Facade: started ok"

    def stop(self):
        # assume already running
        print "Facade: request stop"
        reactor.callFromThread(reactor.stop)
        print "Facade: request stopped ok"
        self.reactorThread.join()
        
    def printC(self, s):
        print "printC,",s
if __name__ == "__main__":
    
    factory = Factory()
    factory.protocol = wire.Echo
    reactor.listenTCP( 7001, factory ) # <-- you don't NEED a protocol, but for example...
    print "Echo on 7001"
    facade = ReactorFacade()
    print "Main: Starting..."
    facade.start()
    print "Main: Sleeping..."
    time.sleep(10)
    print "Main: Stopping..."
    facade.stop()
    print "Main: Finished" # <-- will hang here
    raw_input("43$#$#$")